package com.shunhe.zs_pda

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.google.gson.reflect.TypeToken
import com.ruitu.arad.Arad
import com.ruitu.arad.api.okhttp.Url
import com.ruitu.arad.api.okhttp.response.JsonResponseHandler
import com.ruitu.arad.support.view.BottomNavigationViewEx
import com.ruitu.arad.support.view.NoScrollViewPager
import com.ruitu.arad.util.SizeUtils
import com.ruitu.arad.util.ToastUtils
import com.ruitu.router_module.Logg
import com.ruitu.router_module.bean.EventModel
import com.shunhe.zs_pda.base.Base2Activity
import com.shunhe.zs_pda.base.Gl
import com.shunhe.zs_pda.model.User
import com.shunhe.zs_pda.ui.fragment.ExportFragment
import com.shunhe.zs_pda.ui.fragment.ImportFragment
import com.shunhe.zs_pda.ui.fragment.MineFragment
import com.shunhe.zs_pda.ui.sys.LoginActivity
import com.shunhe.zs_pda.util.find
import com.shunhe.zs_pda.util.openActivity
import org.json.JSONObject

class MainActivity : Base2Activity() {

    lateinit var bnve: BottomNavigationViewEx
    lateinit var vp: NoScrollViewPager
    private var adapter: VpAdapter? = null
    var user: User.UserInfo? = null

    override fun getLayoutRes(): Int = R.layout.activity_main
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bnve = find(R.id.bnve)
        vp = find(R.id.vp)
        vp.offscreenPageLimit = 9
        vp.setScanScroll(false)
        bnve.enableAnimation(false)
        bnve.enableShiftingMode(false)
        bnve.enableItemShiftingMode(false)
        bnve.setIconsMarginTop(SizeUtils.dp2px(10f))
        bnve.setIconSize(23f, 23f)
        bnve.setTextSize(10f)
        bnve.setOnNavigationItemSelectedListener { item: MenuItem? -> true }
        adapter = VpAdapter(supportFragmentManager)
        vp.adapter = adapter
        bnve.setupWithViewPager(vp)

        setHeadTitle("手持PDA")
    }

    override fun onResume() {
        super.onResume()
        reqUserInfo()
    }

    // 获取用户信息
    private fun reqUserInfo() {
        val token = Arad.preferences.getString("token")
        if (TextUtils.isEmpty(token)) {
            openActivity<LoginActivity>(this) {}
            ToastUtils.showShort("请先登录")
            return
        }
        val params: MutableMap<String, String> = HashMap()
        params["token"] = token
        hideProgress()
        Gl.okHttp!!.get().url(Url.GET_USER_INFO).params(params)
            .tag(this).enqueue(this, object : JsonResponseHandler() {
                override fun onFailure(statusCode: Int, error_msg: String) {
                    hideProgress()
                    ToastUtils.showShort("请求失败")
                    Logg.i("reqUserInfo.error_msg = $error_msg")
                }

                override fun onSuccess(statusCode: Int, response: JSONObject) {
                    hideProgress()
                    val code = response.optString("code")
                    val msg = response.optString("msg")
                    val data = response.optString("data")
                    Logg.i("reqUserInfo.code = $code msg = $msg")
                    Logg.i("reqUserInfo.data = $data")
                    if (TextUtils.equals("1", code)) {
                        user = Gl.gson.fromJson<User.UserInfo>(
                            data,
                            object : TypeToken<User.UserInfo?>() {}.type
                        )
                        if (null != user) {
                            Gl.user = user
                            // 延迟一段时间设置极光别名
//                            Handler(Looper.getMainLooper()).postDelayed({
//                                JPushInterface.setAlias(
//                                    application, 1, user!!.jpush_username
//                                )
//                            }, 2000)
                            // 获取用户信息成功
                            Arad.bus.post(EventModel<Any?>(22110951))
                        }
                    } else {
                        // 未登录或已过期
                        if (TextUtils.equals("401", code) || TextUtils.equals("-10010", code)) {
                            startActivity(LoginActivity::class.java)
                        }
                        ToastUtils.showShort(msg)
                    }
                }
            })
    }

    private inner class VpAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm!!) {
        override fun getItem(position: Int): Fragment {
            return if (position == 0) {
                ImportFragment.newInstance("0")
            } else if (position == 1) {
                ExportFragment.newInstance("1")
            } else if (position == 2) {
                MineFragment.newInstance("2")
            } else {
                MineFragment.newInstance("2")
            }
        }

        override fun getCount(): Int {
            return bnve.itemCount
        }
    }

    private val waitTime: Long = 2000
    private var touchTime: Long = 0
    override fun onBackPressed() {
        if (vp.currentItem == 0) {
            val currentTime = System.currentTimeMillis()
            if (currentTime - touchTime >= waitTime) {
                ToastUtils.showShortSafe("再按一次退出程序")
                touchTime = currentTime
            } else {
                val backHome = Intent(Intent.ACTION_MAIN) //启动一个意图,回到桌面
                backHome.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                backHome.addCategory(Intent.CATEGORY_HOME)
                startActivity(backHome)
            }
        } else {
            vp.currentItem = 0
        }
    }

}